const request = require('../../utils/request.js');
// pages/message/message.js
Page({
  data: {
    searchQuery: '',
    chatRooms: [],
    filteredChatRooms: []
  },

  onLoad() {
    // 請求後端接口，獲取聊天記錄
    request.request('/api/message/list', 'GET', { 'pn': 1 })
      .then((res) => {
        console.log(res);

        // 假設返回的數據在 `res.data.list` 中
        const backendData = res.data.list.map((item) => ({
          id: item.id,  // 聊天記錄ID
          name: item.ToUserName,  // 聊天對象名稱
          lastMessage: item.content,  // 最後一條消息
          timestamp: this.formatTimestamp(item.sendTime),  // 格式化時間
          senderId: item.senderId,
          unreadCount: item.read === 0 ? 1 : 0,  // 未讀消息數
          avatar: 'http://106.52.12.104:8080/image' + item.ToUserHeader  // 頭像圖片
        }));

        // 將獲取到的數據設置到 `chatRooms` 和 `filteredChatRooms`
        this.setData({
          chatRooms: backendData,
          filteredChatRooms: backendData
        });
      })
      .catch((error) => {
        console.error("Error fetching chat data:", error);
      });
  },

  formatTimestamp(timestamp) {
    const date = new Date(timestamp);
    return `${date.getHours()}:${date.getMinutes() < 10 ? '0' : ''}${date.getMinutes()} ${date.getHours() >= 12 ? 'PM' : 'AM'}`;
  },

  onInput(event) {
    this.setData({
      searchQuery: event.detail.value
    });

    const searchQuery = this.data.searchQuery.trim().toLowerCase(); // 去除首尾空格並轉換為小寫
    if (searchQuery === '') {
      // 如果搜索內容為空，展示完整數據
      this.setData({
        filteredChatRooms: this.data.chatRooms
      });
    } else {
      // 如果有搜索內容，進行過濾
      const filteredChatRooms = this.data.chatRooms.filter(chatRoom => {
        return chatRoom.name.toLowerCase().includes(searchQuery) ||
               chatRoom.lastMessage.toLowerCase().includes(searchQuery);
      });

      this.setData({
        filteredChatRooms: filteredChatRooms
      });
    }
  },

  onSearch() {
    const searchQuery = this.data.searchQuery.trim().toLowerCase();
    if (searchQuery === '') {
      // 如果搜索內容為空，展示完整數據
      this.setData({
        filteredChatRooms: this.data.chatRooms
      });
    } else {
      const filteredChatRooms = this.data.chatRooms.filter(chatRoom => {
        return chatRoom.name.toLowerCase().includes(searchQuery) ||
               chatRoom.lastMessage.toLowerCase().includes(searchQuery);
      });

      this.setData({
        filteredChatRooms: filteredChatRooms
      });
    }
  },

  gotoChatRoom(event) {
    // 獲取點擊的聊天室的ID
    const chatRoomId = event.currentTarget.dataset.id;
    const name = event.currentTarget.dataset.name;
    const avatar = event.currentTarget.dataset.avatar;
    // 找到點擊的聊天室在 chatRooms 中的索引
    const chatRoomIndex = this.data.chatRooms.findIndex(room => room.id === chatRoomId);
  
    if (chatRoomIndex !== -1) {
      // 取反 unreadCount：如果為 0 就設置為 1，反之為 0
      const updatedUnreadCount = this.data.chatRooms[chatRoomIndex].unreadCount === 0 ? 1 : 0;
  
      // 更新 chatRooms 中對應聊天室的 unreadCount
      this.setData({
        [`chatRooms[${chatRoomIndex}].unreadCount`]: updatedUnreadCount,
        [`filteredChatRooms[${chatRoomIndex}].unreadCount`]: updatedUnreadCount
      });
    }
  
    // 跳轉到相應的聊天室頁面，並攜帶聊天室ID
    wx.navigateTo({
      url: `/subpackages/message-module/pages/chat-room/chat-room?id=${chatRoomId}&name=${name}&avatar=${avatar}`
    });
  }
  
});
